<template>
  <view class="container">
    <view class="wrapper">
      <view class="main">
        <view class="card">
          <view class="row" @click="showWayPopup = true">
            <view class="label">取货方式</view>
            <view class="info">
              <text class="way">{{ pickUpType === 1 ? '骑手取货' : '用户送回' }}</text>
              <text class="iconfont icon-arrow-right"></text>
            </view>
          </view>
          <view class="row" @click="showTimePopup = true">
            <view class="label">取货时间</view>
            <view class="info">
              <text class="way">{{ dateType === 'today' ? '今天' : '明天' }} {{ timeLabel }}</text>
              <text class="iconfont icon-arrow-right"></text>
            </view>
          </view>
        </view>
        <view class="card">
          <view class="title">说明</view>
          <view class="explain">
            <view>1. 设置取货方式前，请与用户确认好之后再操作，以免客诉。</view>
            <view>2. 取货方式仅可选择“骑手取货”或“用户送回”。</view>
            <view>3. “商家上门”取货的方式暂不支持，如有需要，可至抖店商家版APP后台操作。</view>
          </view>
        </view>
      </view>
      <view class="footer">
        <u-button type="primary" shape="circle" :customStyle="customStyle" @click="submit">提交</u-button>
      </view>
    </view>
    <u-popup
      v-model="showWayPopup"
      border-radius="24"
      :closeable="true"
      mode="bottom"
      :safe-area-inset-bottom="true"
    >
      <view class="way-popup">
        <view class="popup-header">选择取货方式</view>
        <view class="popup-body">
          <view class="way">
            <view class="way-item" @click="selectDeliveryWay(1)">
              <view class="way-info">
                <view class="way-name">骑手取货</view>
                <view class="way-detail">呼叫平台骑手取退货，将会产生运费，退货运费承担方将由平台判定。</view>
              </view>
              <view class="way-choice" :class="{ active: pickUpType === 1 }">
                <view class="dot" v-if="pickUpType === 1" />
              </view>
            </view>
            <view class="way-item" @click="selectDeliveryWay(3)">
              <view class="way-info">
                <view class="way-name">用户送回</view>
                <view class="way-detail">退货由用户送回门店，在售后责任方是用户时，可与用户协商后选择。</view>
              </view>
              <view class="way-choice" :class="{ active: pickUpType === 3 }">
                <view class="dot" v-if="pickUpType === 3" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
    <u-popup
      v-model="showTimePopup"
      border-radius="24"
      :closeable="true"
      :safe-area-inset-bottom="true"
      mode="bottom"
    >
      <view class="time-popup">
        <view class="popup-header">选择取货时间</view>
        <view class="popup-body">
          <view class="left">
            <view class="left-item" :class="{ active: dateType === 'today' }" @click="selectDateType('today')">
              <view class="left-text" :class="{ active: dateType === 'today' }">今天</view>
            </view>
            <view class="left-item" :class="{ active: dateType === 'tomorrow' }" @click="selectDateType('tomorrow')">
              <view class="left-text" :class="{ active: dateType === 'tomorrow' }">明天</view>
            </view>
          </view>
          <view class="right">
            <view class="right-item"
                  v-for="item in pickUpTime" :key="item"
                  @click="selectPickUpTime(item)"
                  :class="{ active: item.timestamp.bookTimeBegin === bookTimeBegin }"
            >{{ item.label }}</view>
            <u-empty v-if="!pickUpTime.length" text="暂无可选时间"></u-empty>
          </view>
        </view>
        <view class="popup-footer" />
      </view>
    </u-popup>
  </view>
</template>

<script>
import * as RefundApi from '@/api/order/refund'

export default {
  data() {
    return {
      background: {
        backgroundColor: '#2D71FD',
        color: '#ffffff',
      },
      customStyle: { height: '96rpx' },
      showWayPopup: false,
      // 1骑手取货 3用户送回
      pickUpType: 1,
      showTimePopup: false,
      // 预约时间
      bookTimeBegin: '',
      bookTimeEnd: '',
      dateType: '',
      todayTime: [],
      tomorrowTime: [],
      timeLabel: '',
      channelRefundOrderNo: '',
      thirdChannelId: ''
    }
  },
  computed: {
    pickUpTime() {
      return this.dateType === 'today' ? this.todayTime : this.tomorrowTime
    }
  },
  watch: {
    pickUpTime: {
      handler(nVal, oVal) {
        if (nVal && nVal !== oVal && !this.timeLabel) {
          const defaultPickUpTime = nVal[0]
          this.selectPickUpTime(defaultPickUpTime)
        }
      },
      deep: true
    },
    showTimePopup: {
      handler(nVal) {
        if (nVal) this.initTodayTime()
      }
    }
  },
  onLoad({ channelRefundOrderNo, thirdChannelId }) {
    this.channelRefundOrderNo = channelRefundOrderNo
    this.thirdChannelId = thirdChannelId
    this.initTodayTime(true)
    this.initTomorrowTime()
  },
  methods: {
    initTodayTime(setDefault = false) {
      const today = this.$moment().startOf('day').format('YYYY-MM-DD')
      const now = new Date()
      let hours = now.getHours()
      const minutes = now.getMinutes()
      if (minutes >= 30) hours += 1
      if(setDefault) this.dateType = hours > 18 ? 'tomorrow' : 'today'
      let todayRange = []
      while(hours < 19) {
        todayRange.push(hours)
        hours++
      }
      this.todayTime = this.formatData(today, todayRange)
    },
    initTomorrowTime() {
      const tomorrow = this.$moment().add(1, 'days').startOf('day').format('YYYY-MM-DD')
      let tomorrowRange = []
      let startHour = 9
      while(startHour < 19) {
        tomorrowRange.push(startHour)
        startHour++
      }
      this.tomorrowTime = this.formatData(tomorrow, tomorrowRange)
    },
    /**
     * 格式化取货时间数据
     * @param {String} date 日期(YYYY-MM-DD)
     * @param {Array} range 可选时间范围
     */
    formatData(date, range) {
      return range.map(item => {
        const _item = item < 10 ? `0${item}` : item
        const label = `${_item}:00 ~ ${item + 1}:00`
        const startTime = this.$moment(`${date} ${_item}:00:00`).format()
        const startTimestamp = (this.$moment(startTime).valueOf()) / 1000
        const endTime = this.$moment(`${date} ${item + 1}:00:00`).format()
        const endTimestamp = (this.$moment(endTime).valueOf()) / 1000
        return {
          label,
          timestamp: {
            bookTimeBegin: startTimestamp,
            bookTimeEnd: endTimestamp
          }
        }
      })
    },
    selectDeliveryWay(way) {
      this.pickUpType = way
      this.showWayPopup = false
    },
    selectDateType(type) {
      this.dateType = type
      if (type === 'today') this.initTodayTime()
    },
    selectPickUpTime(data) {
      const { label, timestamp } = data
      this.timeLabel = label
      this.bookTimeBegin = timestamp.bookTimeBegin
      this.bookTimeEnd = timestamp.bookTimeEnd
      this.showTimePopup = false
    },
    submit() {
      const params = {
        pickUpType: this.pickUpType,
        bookTimeBegin: this.bookTimeBegin,
        bookTimeEnd: this.bookTimeEnd,
        channelRefundOrderNo: this.channelRefundOrderNo,
        thirdChannelId: this.thirdChannelId
      }
      RefundApi.logisticsFill(params).then(res => {
        const { data } = res
        if (data) {
          this.$success('操作完成')
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    background: #f2f2f3;

    .main {
      width: 100%;
      padding: 24rpx;
    }

    .footer {
      width: 100%;
      background: #fff;
      padding: 16rpx 32rpx 40rpx;
    }
  }

  .card {
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 16rpx;

    .row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx;

      .label {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        margin-right: 24rpx;
      }

      .info {
        flex: 1;
        font-size: 26rpx;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .way {
          margin-right: 8rpx;
        }

        .iconfont {
          font-size: 40rpx;
          color: #999;
        }
      }
    }

    .title {
      font-size: 28rpx;
      font-weight: 500;
      padding: 24rpx 24rpx 0;
    }

    .explain {
      font-size: 26rpx;
      color: #666;
      padding: 16rpx 24rpx 24rpx;

      view {
        padding-left: 8rpx;
        margin-bottom: 8rpx;
      }
    }
  }

  .popup-header {
    height: 50rpx;
    line-height: 50rpx;
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
    text-align: center;
    margin-top: 54rpx;
    margin-bottom: 40rpx;
  }

  .way-popup {
    display: flex;
    flex-direction: column;
    min-height: 50vh;
    background: #f2f2f3;

    .popup-body {
      padding: 0 24rpx;

      .way {
        background: #fff;
        border-radius: 16rpx;
        padding: 24rpx 32rpx;

        .way-item {
          display: flex;
          align-items: center;
          padding: 16rpx 0 24rpx;
          border-bottom: 1rpx solid #eee;

          &:last-of-type {
            margin-top: 20rpx;
          }

          .way-info {
            flex: 1;

            .way-name {
              font-size: 28rpx;
              font-weight: 500;
              color: #333;
              margin-bottom: 16rpx;
            }

            .way-detail {
              font-size: 26rpx;
              color: #999;
            }
          }

          .way-choice {
            position: relative;
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
            border: 2rpx solid #cdcdcd;
            box-sizing: border-box;
            margin-left: 32rpx;

            &.active {
              border-color: #2D71FD;
            }

            .dot {
              position: absolute;
              top: 8rpx;
              left: 8rpx;
              width: 20rpx;
              height: 20rpx;
              background: #2D71FD;
              border-radius: 50%;
            }
          }
        }
      }
    }
  }

  .time-popup {
    display: flex;
    flex-direction: column;
    min-height: 50vh;
    max-height: 80vh;
    font-size: 26rpx;
    background: #fff;

    .popup-body {
      flex: 1;
      display: flex;
      overflow-y: scroll;

      .left {
        width: 250rpx;
        background: #f5f5f5;

        .left-item {
          height: 100rpx;
          padding: 32rpx 0;

          &.active {
            background: #fff;
          }

          .left-text {
            position: relative;
            padding: 0 24rpx;

            &.active {
              font-weight: 500;
              color: #2D71FD;
            }

            &.active:before {
              content: '';
              width: 4rpx;
              height: 36rpx;
              background: #2D71FD;
              position: absolute;
              top: 0;
              left: 0;
              border-radius: 4rpx;
            }
          }
        }
      }

      .right {
        flex: 1;
        overflow-y: scroll;

        .right-item {
          height: 100rpx;
          padding: 32rpx 0 0 109rpx;

          &.active {
            font-weight: 500;
            color: #2D71FD;
          }
        }
      }
    }
  }
}
</style>
